package com.sunday.pinxinghui.model.lifecircle;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.view.View;
import android.webkit.WebView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.sunday.common.adapter.CommenAdapter;
import com.sunday.common.adapter.ViewHolder;
import com.sunday.common.base.BaseActivity;
import com.sunday.common.model.ResultDO;
import com.sunday.common.utils.ToastUtils;
import com.sunday.common.widgets.NoScrollListview;
import com.sunday.pinxinghui.R;
import com.sunday.pinxinghui.base.BaseApplication;
import com.sunday.pinxinghui.base.NeedPhonePermissionActivity;
import com.sunday.pinxinghui.entity.ShopDetail;
import com.sunday.pinxinghui.model.login.LoginActivity;
import com.sunday.pinxinghui.model.mine.CouponListActivity;
import com.sunday.pinxinghui.network.ApiClient;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * Created by 刘涛 on 2017/8/24.
 */

public class ShopDetailActivity extends NeedPhonePermissionActivity {

    @Bind(R.id.title_view)
    TextView titleView;
    @Bind(R.id.right_btn)
    ImageView rightBtn;
    @Bind(R.id.shop_img)
    ImageView shopImg;
    @Bind(R.id.shop_title)
    TextView shopTitle;
    @Bind(R.id.shop_desc)
    TextView shopDesc;
    @Bind(R.id.shop_addr)
    TextView shopAddr;
    @Bind(R.id.list_view)
    NoScrollListview listView;
    @Bind(R.id.shop_rule)
    TextView shopRule;
    @Bind(R.id.addr_extra_menu1)
    TextView addrExtraMenu1;
    @Bind(R.id.addr_extra_menu2)
    TextView addrExtraMenu2;
    @Bind(R.id.addr_extra_layout)
    LinearLayout addrExtraLayout;

    private int shopId;
    private long memberId;
    private ShopDetail shopDetail;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_shop_detail);
        ButterKnife.bind(this);
        titleView.setText("商家详情");
        shopId = getIntent().getIntExtra("shopId", 0);
        memberId = BaseApplication.getInstance().getMember().getId();
        getData();

    }

    @Override
    public boolean onRequestCallPermissionSuccessed() {
        String number = shopDetail.getShop().getMobile();
        if (TextUtils.isEmpty(number)) {
            // 提醒用户
            // 注意：在这个匿名内部类中如果用this则表示是View.OnClickListener类的对象，
            // 所以必须用MainActivity.this来指定上下文环境。
            ToastUtils.showToast(mContext, "号码不能为空");
        } else {
            // 拨号：激活系统的拨号组件
            Intent intent = new Intent(); // 意图对象：动作 + 数据
            intent.setAction(Intent.ACTION_CALL); // 设置动作
            Uri data = Uri.parse("tel:" + number); // 设置数据
            intent.setData(data);
            startActivity(intent); // 激活Activity组件
        }
        return true;


    }

    private void getData() {
        Call<ResultDO<ShopDetail>> call = ApiClient.getApiAdapter().getShopDetail(shopId, memberId);
        call.enqueue(new Callback<ResultDO<ShopDetail>>() {
            @Override
            public void onResponse(Call<ResultDO<ShopDetail>> call, Response<ResultDO<ShopDetail>> response) {
                if (isFinish || response.body() == null) {
                    return;
                }
                if (response.body().getCode() == 0) {
                    shopDetail = response.body().getResult();
                    updateView(shopDetail);
                }
            }

            @Override
            public void onFailure(Call<ResultDO<ShopDetail>> call, Throwable t) {

            }
        });
    }

    private void updateView(ShopDetail shopDetail) {
        if (shopDetail == null) {
            return;
        }
        Glide.with(mContext)
                .load(shopDetail.getShop().getImage())
                .error(R.mipmap.ic_default)
                .into(shopImg);
        shopTitle.setText(shopDetail.getShop().getName());
        shopDesc.setText(shopDetail.getShop().getDesc());
        shopAddr.setText(shopDetail.getShop().getAddress());
        shopRule.setText(shopDetail.getHtml());
        if (shopDetail.getCoupons() != null && shopDetail.getCoupons().size() > 0) {
            listView.setAdapter(new CommenAdapter<ShopDetail.CouponsBean>(mContext, shopDetail.getCoupons(), R.layout.list_shop_coupon_item) {
                @Override
                public void convert(ViewHolder helper, ShopDetail.CouponsBean item, int position) {
                    bind(helper, item, position);
                }
            });
        }
    }

    private void bind(ViewHolder helper, final ShopDetail.CouponsBean item, int position) {
        ImageView imageView = helper.getView(R.id.coupon_img);
        Glide.with(mContext)
                .load(item.getImage())
                .error(R.mipmap.ic_default)
                .into(imageView);
        ((TextView) helper.getView(R.id.coupon_title)).setText(item.getTitle());
        ((TextView) helper.getView(R.id.coupon_time)).setText("有效期至" + item.getEndTime());
        ((TextView) helper.getView(R.id.coupon_point)).setText(item.getScore() + "积分");
        helper.getView(R.id.btn_exchange).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
                builder.setTitle("温馨提示");
                builder.setMessage("确认兑换吗");
                builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });
                builder.setPositiveButton("确认", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        exchangeCoupon(item.getId());
                        dialog.dismiss();
                    }
                });
                builder.show();
            }
        });
        helper.getView(R.id.coupon_layout).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                intent = new Intent(mContext, CouponDetailActivity.class);
                intent.putExtra("couponId", item.getId());
                intent.putExtra("endDate", item.getEndTime());
                startActivity(intent);
            }
        });
    }

    private void exchangeCoupon(int couponId) {
        showLoadingDialog(0);
        Call<ResultDO> call = ApiClient.getApiAdapter().couponExchange(couponId, memberId);
        call.enqueue(new Callback<ResultDO>() {
            @Override
            public void onResponse(Call<ResultDO> call, Response<ResultDO> response) {
                dissMissDialog();
                if (isFinish || response.body() == null) {
                    return;
                }
                if (response.body().getCode() == 0) {
                    AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
                    builder.setTitle("温馨提示");
                    builder.setMessage("兑换成功,是否立即使用？");
                    builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                        }
                    });
                    builder.setPositiveButton("去使用", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            intent = new Intent(mContext, CouponListActivity.class);
                            intent.putExtra("page", 1);
                            startActivity(intent);
                            dialog.dismiss();
                        }
                    });
                    builder.show();
                } else {
                    ToastUtils.showToast(mContext, response.body().getMessage());
                }
            }

            @Override
            public void onFailure(Call<ResultDO> call, Throwable t) {
                dissMissDialog();
                ToastUtils.showToast(mContext, R.string.network_error);
            }
        });
    }

    @OnClick({R.id.addr_extra_menu1, R.id.addr_extra_menu2})
    void onClick(View v) {
        switch (v.getId()) {
            case R.id.addr_extra_menu1:
                AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
                builder.setTitle("温馨提示");
                builder.setMessage("确认拨打商家电话吗");
                builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });
                builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        checkCallPermission();

                    }
                });
                builder.show();
                break;
            case R.id.addr_extra_menu2:
                String desLatit = shopDetail.getShop().getLat();
                String desLongit = shopDetail.getShop().getLng();
                String oriLatit = BaseApplication.getInstance().getLati();
                String oriLongit = BaseApplication.getInstance().getLongti();
                if (isAvilible(mContext, "com.baidu.BaiduMap")) {//传入指定应用包名
                    Intent intent = new Intent();
                    String uri = String.format("baidumap://map/direction?origin=%1$s,%2$s&destination=%3$s,%4$s&mode=driving", oriLatit, oriLongit, desLatit, desLongit);
                    intent.setData(Uri.parse(uri));
                    mContext.startActivity(intent); //启动调用

                } else {//未安装
                    //market为路径，id为包名
                    //显示手机上所有的market商店
                    Toast.makeText(mContext, "您尚未安装百度地图", Toast.LENGTH_LONG).show();
                    Uri uri = Uri.parse("market://details?id=com.baidu.BaiduMap");
                    Intent intent = new Intent(Intent.ACTION_VIEW, uri);
                    mContext.startActivity(intent);
                }
//                if (isAvilible(mContext, "com.autonavi.minimap")) {
//                    Intent intent = new Intent();
//                    String uri = String.format("androidamap://route?sourceApplication=品行惠&slat=%1$s&slon=%2$s&dlat=%3$s&dlon=%4$s&dev=0&m=0&t=1", oriLatit, oriLongit, desLatit, desLongit);
//                    intent.setData(Uri.parse(uri));
//                    mContext.startActivity(intent); //启动调用
//                } else {
//                    Toast.makeText(mContext, "您尚未安装高德地图", Toast.LENGTH_LONG).show();
//                    Uri uri = Uri.parse("market://details?id=com.autonavi.minimap");
//                    Intent intent = new Intent(Intent.ACTION_VIEW, uri);
//                    mContext.startActivity(intent)
//                 }
                break;
        }
    }

    /**
     * 检查手机上是否安装了指定的软件
     *
     * @param context
     * @param packageName：应用包名
     * @return
     */
    public static boolean isAvilible(Context context, String packageName) {
        //获取packagemanager
        final PackageManager packageManager = context.getPackageManager();
        //获取所有已安装程序的包信息
        List<PackageInfo> packageInfos = packageManager.getInstalledPackages(0);
        //用于存储所有已安装程序的包名
        List<String> packageNames = new ArrayList<String>();
        //从pinfo中将包名字逐一取出，压入pName list中
        if (packageInfos != null) {
            for (int i = 0; i < packageInfos.size(); i++) {
                String packName = packageInfos.get(i).packageName;
                packageNames.add(packName);
            }
        }
        //判断packageNames中是否有目标程序的包名，有TRUE，没有FALSE
        return packageNames.contains(packageName);
    }
}
